import fetch from "isomorphic-fetch";
import { Toast } from "antd-mobile";
import yhTools from "../yh";
import { alertOneButt } from "../base";

/**
 * 网络请求
 *
 * @param {*} objs
 *
 * objs
 * -url     请求地址
 * -header  请求头
 * -params  参数
 */
export function postRequest(objs) {
	if (yhTools.platform() == "web") {
		let _postParms = {
			method: "POST",
			mode: "cors",
			headers: {
				"Content-Type": "application/json;charset=UTF-8",
				...objs.header
			},
			body: JSON.stringify(objs.params)
		};
		return fetch(objs.url, _postParms).then(resp => resp.json());
	} else {
		return new Promise(function (resolve, reject) {
			if (!window.YHAuthorize) {
				reject();
				Toast.hide();
				return;
			}
			window.YHAuthorize.callHandler("Http_Request", objs, resp => {
				Toast.hide();
				console.log(
					`请求成功`,
					`接口地址：${objs.url}`,
					`参数`,
					objs.params,
					`结果`,
					resp
				);
				if (resp.status === "1000") {
					let httpResp = resp.data;
					resolve(httpResp);
					if (httpResp.code === "99998" || httpResp.code === "99999") {
						// 用户信息失效
						setTimeout(() => {
							//留时间Toast展示
							yhTools.closePage();
						}, 2000);
					}
				} else {
					// 网络请求失败
					reject(resp);
					alertOneButt("当前网络异常!", "好的");
				}
			});
		});
	}
}

//上传图片
export function uploadImage(objs) {
	if (yhTools.platform() === "web") {
		let resp = {
			status: "1000",
			data: {
				code: "0"
			}
		};
		return new Promise(function (resolve) {
			resolve(resp);
		});
	} else {
		return new Promise(function (resolve, reject) {
			window.YHAuthorize.callHandler("SDK_UpLoadImage", objs, resp => {
				Toast.hide();

				if (resp.status === "1000") {
					// 请求成功
					if (resp.data.code === "0") {
						// 请求成功
						resolve(resp.data);
					} else {
						resolve(resp.data);
						Toast.info(resp.data.message, 2);
					}
				} else {
					reject(resp);
					Toast.info("系统在开小差，请稍后再试。", 2);
				}
			});
		});
	}
}
